const Http = require('http')
const fs = require('fs')
const Route = require('./route')
const formidable = require('formidable')

const port = 3001

const httpStart = () => {
  // 创建 HTTP 服务
  const server = Http.createServer((req, response) => {
    const form = formidable({ multiples: false })
    form.parse(req, (err, fields, files) => {
      if (err) {
        responseEnd(err)
      }
      const file = files
      console.log(file, 8888888888888)
      saveFile(file)
    })
    Route.apiServer(req, response) // 普通HTTP服务
  }).listen(port, function () {
    console.log('创建HTTP', port)
    console.log(`server is running on http://localhost:${port}`)
  })

  return server
}

function saveFile(file) {
  // 读文件
  console.log(file.filepath)
  fs.readFile(file.path, (err, data) => {
    if (err) {
      responseEnd(err)
    }
    const basePath = '../public/files'
    // 创建目录
    createDir(basePath)
    // 写入文件
    fs.writeFile(path.join(basePath, file.name), data, async (err) => {
      if (err) {
        responseEnd(err)
      }
      responseEnd()
    })
  })
}
/**
 * 判断目录是否存在，不存在则创建
 * { recursive: true } 表示多层目录时递归创建
 */
function createDir(path) {
  if (!fs.existsSync(path)) {
    fs.mkdirSync(path, { recursive: true })
  }
}
/**
 * 服务器响应
 */
function responseEnd(err) {
  if (err) {
    console.log(err)
    result.statusCode = 500
    result.end('fail')
  } else {
    result.statusCode = 200
    result.end('success')
  }
}


exports.httpStart = httpStart
